package com.smartHome.service.impl;

import com.smartHome.exception.AccountNotFoundException;
import com.smartHome.mapper.UserMapper;

import com.smartHome.pojo.dto.UserDTO;
import com.smartHome.pojo.entity.User;
import com.smartHome.service.UserService;
import com.smartHome.utils.Md5Util;
import com.smartHome.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User findByEmail(String email) {
        User user = userMapper.findByEmail(email);
        return user;
    }

    @Override
    public void register(User user) {
        String password = Md5Util.getMD5String(user.getPassword());
        user.setPassword(password);
        userMapper.add(user);
    }

    @Override
    public User update(UserDTO userDTO) {
        Map map = ThreadLocalUtil.get();
        String email = (String) map.get("email");
        //根据邮箱查询用户
        User user = userMapper.findByEmail(email);

        if (user == null) {
            throw new AccountNotFoundException("用户不存在");
        }

        //密码对比
        String oldPassword = Md5Util.getMD5String(userDTO.getOldPassword());
        if (!oldPassword.equals(user.getPassword())) {
            throw new AccountNotFoundException("旧密码不正确");
        }


        //密码验证通过，开始更新用户数据
        // 更新新密码
        String newPassword = Md5Util.getMD5String(userDTO.getNewPassword());
        if (userDTO.getNewPassword() != null) {
            user.setPassword(newPassword);
        }
        // 更新其他信息
        if (userDTO.getUsername() != null) {
            user.setUsername(userDTO.getUsername());
        }

        if (userDTO.getAvatar() != null) {
            user.setAvatar(userDTO.getAvatar());
        }

        userMapper.update(user);

        user.setPassword("***");
        return user;
    }

}
